package com.lagou.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author yutao
 * @create 2020-06-13 16:29
 **/
@Configuration
public class ServerConfig {


    @Autowired
    private ApplicationContext applicationContext;

    @Value("${provider.name:provider1}")
    private String name;
    @Value("${provider.ip:127.0.0.1}")
    private String ip;
    @Value("${provider.port:8999}")
    private Integer port;


    @Bean
    public Server startServer() throws Exception {
        Server bootServer = new Server();
        bootServer.setApplicationContext(applicationContext);
        //启动服务器
        bootServer.startServer(ip, port);
        regiserZK(name,ip,port);
        return bootServer;
    }


    // 创建会话
    private static void regiserZK(String name,String ip,Integer port) throws Exception {

        //不使用fluent编程风格

        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);

        // 使用fluent编程风格
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(10000)
                .connectionTimeoutMs(10000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace("base")  // 独立的命名空间 /base
                .build();

        client.start();

        System.out.println("会话创建了");

        // 创建节点
        String path = "/"+name;
        String s = client.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL).forPath(path, (ip+":"+port).getBytes());

        System.out.println("节点递归创建成功，该节点路径" + s);


    }

}
